package com.group2.operations.mapper;

import com.group2.operations.model.User;
import com.group2.operations.model.vo.UserInfoVO;
import org.apache.ibatis.annotations.*;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

@Repository
@Mapper
public interface UserMapper {
    /**
     * 根据用户名查找用户
     * @param name 用户名
     * @return 查找到的用户
     */
    @Select("select * from user where name=#{name}")
    @Results({
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "name", property = "name"),
            @Result(column = "pwd", property = "pwd"),
            @Result(column = "rid", property = "role", one = @One(select = "com.group2.operations.mapper.RoleMapper.queryRoleById"))
    })
    User queryUserByName(@Param("name") String name);

    /**
     * 插入一条用户数据
     * @param user 用户
     */
    @Insert("insert into user(id, name, pwd, rid) values (null, #{name}, #{pwd}, 1)")
    void insertUser(User user) throws DataAccessException;

    /**
     * 更新用户个人信息
     * @param vo 个人信息对象
     * @param username 用户名
     * @throws DataAccessException
     */
    @Update("update user set `real`=#{info.real}, `number`=#{info.number}, `phone`=#{info.phone}, `email`=#{info.email}, `infoUpdated`=1 where `name`=#{name}")
    void updateUserInfo(@Param("info") UserInfoVO vo, @Param("name") String username) throws DataAccessException;

    /**
     * 获取用户个人信息
     * @param name 用户名
     * @return 用户信息对象
     */
    @Select("select `real`, `number`, `phone`, `email` from user where `name`=#{name}")
    UserInfoVO getUserInfoByName(String name);

    /**
     * 改变角色为代理商
     * @param username 用户名
     */
    @Update("update user set rid=2 where name=#{username}")
    void changeRoleToAgent(String username);
}
